package com.atguigu.srb.core.service.impl;

import com.atguigu.common.exception.Assert;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.srb.core.enums.BorrowAuthEnum;
import com.atguigu.srb.core.enums.BorrowInfoStatusEnum;
import com.atguigu.srb.core.enums.BorrowerStatusEnum;
import com.atguigu.srb.core.enums.UserBindEnum;
import com.atguigu.srb.core.mapper.BorrowerMapper;
import com.atguigu.srb.core.mapper.IntegralGradeMapper;
import com.atguigu.srb.core.mapper.UserInfoMapper;
import com.atguigu.srb.core.pojo.VO.BorrowInfoApprovalVO;
import com.atguigu.srb.core.pojo.VO.BorrowerDetailVO;
import com.atguigu.srb.core.pojo.entity.BorrowInfo;
import com.atguigu.srb.core.mapper.BorrowInfoMapper;
import com.atguigu.srb.core.pojo.entity.Borrower;
import com.atguigu.srb.core.pojo.entity.IntegralGrade;
import com.atguigu.srb.core.pojo.entity.UserInfo;
import com.atguigu.srb.core.service.BorrowInfoService;
import com.atguigu.srb.core.service.BorrowerService;
import com.atguigu.srb.core.service.DictService;
import com.atguigu.srb.core.service.LendService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 借款信息表 服务实现类
 * </p>
 *
 * @author ZLHao
 * @since 2021-07-12
 */
@Service
public class BorrowInfoServiceImpl extends ServiceImpl<BorrowInfoMapper, BorrowInfo> implements BorrowInfoService {


    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private IntegralGradeMapper integralGradeMapper;

    @Resource
    private DictService dictService;

    @Autowired
    private BorrowerService borrowerService;

    @Autowired
    private BorrowerMapper borrowerMapper;

    @Autowired
    private LendService lendService;


    @Override
    public Long getBorrowAmount(Long userId) {

        // 首先查出来用户积分
        UserInfo userInfo = userInfoMapper.selectById(userId);
        // 获取用户积分
        Integer integral = userInfo.getIntegral();

        // 根据积分查询在哪个借款区间
        QueryWrapper<IntegralGrade> queryWrapper = new QueryWrapper<>();
        // 大于
         queryWrapper.le("integral_start",integral);
         // 小于
         queryWrapper.ge("integral_end",integral);
        IntegralGrade integralGrade = integralGradeMapper.selectOne(queryWrapper);
        BigDecimal borrowAmount = integralGrade.getBorrowAmount();
        Long borr = borrowAmount.longValue();
        return borr;
    }

    @Override
    public void save(BorrowInfo borrowInfo, Long userId) {

        // 先判断该用户的借款额度审核的状态
        // 判断绑定状态
        UserInfo userInfo = userInfoMapper.selectById(userId);
        // 获取绑定状态
        Integer bindStatus = userInfo.getBindStatus();
        Assert.isTrue(bindStatus.intValue() == UserBindEnum.BIND_OK.getStatus(), ResponseEnum.USER_NO_BIND_ERROR);
//        获取用户的借款额度审核的状态
        Integer borrowAuthStatus = userInfo.getBorrowAuthStatus();
        Assert.isTrue(borrowAuthStatus.intValue() == BorrowerStatusEnum.AUTH_OK.getStatus(), ResponseEnum.USER_NO_AMOUNT_ERROR);

        // 判断额度是否足够
        BigDecimal b = borrowInfo.getAmount();
        long aMount = b.longValue();
        Long borrowAmount = getBorrowAmount(userId);

        Assert.isTrue(aMount<borrowAmount,ResponseEnum.USER_AMOUNT_LESS_ERROR);
        // 存储数据
        borrowInfo.setUserId(userId);
        // 年利率转化为小数
        borrowInfo.setBorrowYearRate(borrowInfo.getBorrowYearRate().divide(new BigDecimal(100)));
        // 设置状态
        borrowInfo.setStatus(BorrowInfoStatusEnum.CHECK_RUN.getStatus());
        // insert
        baseMapper.insert(borrowInfo);

    }

    @Override
    public Integer getBorrowInfoStatus(Long userId) {

        QueryWrapper<BorrowInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("status").eq("user_id",userId);

        List<BorrowInfo> borrowInfos = baseMapper.selectList(queryWrapper);

        if (borrowInfos == null){ // 说明现在还没有提交借款申请
            return BorrowInfoStatusEnum.NO_AUTH.getStatus();
        }

        Integer status = null;
        for (BorrowInfo borrowInfo : borrowInfos) {
            status = borrowInfo.getStatus();
        }
        return status;
    }

    @Override
    public List<BorrowInfo> listAll() {

        List<BorrowInfo> borrowInfos = baseMapper.selectAll();
        for (BorrowInfo borrowInfo : borrowInfos) {
            // 还款方式
            String return_method = dictService.getNameByParentDictCodeAndValue("returnMethod", borrowInfo.getReturnMethod());
            // 资金用途
            String money_use = dictService.getNameByParentDictCodeAndValue("moneyUse", borrowInfo.getMoneyUse());
            // 状态
            String msgByStatus = BorrowInfoStatusEnum.getMsgByStatus(borrowInfo.getStatus());
            borrowInfo.getParam().put("returnMethod",return_method);
            borrowInfo.getParam().put("moneyUse",money_use);
            borrowInfo.getParam().put("status",msgByStatus);
        }
        return borrowInfos;
    }

    @Override
    public HashMap<String, Object> showById(Long id) {

        HashMap<String, Object> hashMap = new HashMap<>();
        // 查询借款信息
        BorrowInfo borrowInfo = baseMapper.selectById(id);
        // 还款方式
        String return_method = dictService.getNameByParentDictCodeAndValue("returnMethod", borrowInfo.getReturnMethod());
        // 资金用途
        String money_use = dictService.getNameByParentDictCodeAndValue("moneyUse", borrowInfo.getMoneyUse());
        // 状态
        String msgByStatus = BorrowInfoStatusEnum.getMsgByStatus(borrowInfo.getStatus());
        borrowInfo.getParam().put("returnMethod",return_method);
        borrowInfo.getParam().put("moneyUse",money_use);
        borrowInfo.getParam().put("status",msgByStatus);


        // 查询 借款人信息
        QueryWrapper<Borrower> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",borrowInfo.getUserId());
        Borrower borrower = borrowerMapper.selectOne(queryWrapper);
        // 将信息转换
        BorrowerDetailVO borrowerDetailVOById = borrowerService.getBorrowerDetailVOById(borrower.getId());

        // 加入map
        hashMap.put("borrowInfo",borrowInfo);
        hashMap.put("borrower",borrowerDetailVOById);
        return hashMap;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void approval(BorrowInfoApprovalVO borrowInfoApprovalVO) {

        // 修改借款状态
        Integer status = borrowInfoApprovalVO.getStatus();

        BorrowInfo borrowInfo = baseMapper.selectById(borrowInfoApprovalVO.getId());
        borrowInfo.setStatus(status);
        baseMapper.updateById(borrowInfo);

        // 审核通过创建标的
        if (borrowInfoApprovalVO.getStatus().intValue() == BorrowInfoStatusEnum.CHECK_OK.getStatus().intValue()){
            lendService.createLend(borrowInfoApprovalVO,borrowInfo);
        }




    }
}
